<template>
  <!-- 好友主页 好友详情页 -->
  <div class="friends_profile_page" ref="scrollContainer">
    <NavBar title="" :showPlaceholder="false">
      <template #left>
        <Icon name="zuojiantou" size="20" color="#fff" @click="handleBackClick" />
      </template>

    </NavBar>
    <div class="my_title_background"
      :style="{ height: backgroundHeight + 'px', transform: `scale(${backgroundScale})`, '--scale': backgroundScale }">
      <img class="background" src="http://43.138.15.137:8080/assets/img/281578538336_.pic_hd.e816ad71.jpg" alt="">
    </div>
    <div class="profile" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"
      @mousedown="handleMouseDown" :style="{ transform: `translate(0px, 0px) scale(1) translateZ(0px)` }">
      <div class="avatar_wrap">
        <img class="avatar" :src="userinfo?.userAvatar" alt="">
      </div>
      <div class="name_wrap">
        <div class="name">
          {{ userinfo?.userNickname || '用户昵称' }}
        </div>
        <div class="subname">
          抖音号: {{ userinfo?.userId || '用户ID' }}
        </div>
        <!-- 是否关注 -->
        <div class="follow" :class="{ 'active': userinfo?.myRelation === 'follow' || userinfo?.myRelation === 'both' }"
          @click="handleFollowClick">
          {{
            userinfo?.myRelation === 'none' ? '关注' :
              userinfo?.myRelation === 'follow' ? '已关注' :
                userinfo?.myRelation === 'both' ? '相互关注' : '关注'
          }}
        </div>
      </div>
      <div class="desc_wrap">
        <div class="desc">{{ userinfo?.userDesc || '用户描述' }}</div>
        <div class="desc_wrap_info">
          <div class="gender">
            <Icon :name="userinfo?.userGender === '男' ? 'nanxing' : 'women-line'" size="12"
              :color="userinfo?.userGender === '男' ? '#448fe0' : '#ec407a'" />
            <span>{{ userinfo?.userGender === '男' ? '男' : '女' || '性别' }}</span>
          </div>
          <div class="desc_wrap_info_age">
            <span>{{ userinfo?.userAge || '年龄' }}岁</span>
          </div>
          <!-- 地址 -->
          <div class="desc_wrap_info_address">
            <span>{{ userinfo?.userAddress || '地址' }}</span>
          </div>
        </div>

      </div>
      <div class="num_wrap">
        <div class="li">{{ likeNum }}获赞</div>
        <div class="li" @click="handleShowTAsFocusPage">{{ followNum }}关注</div>
        <div class="li" @click="handleShowTAsFansPage">{{ fansNum }}粉丝</div>
      </div>
      <Tab v-model="currentIndex" @Tabchange="handleTabChange">
        <TabItem :label="`作品${workNum}`">
          <div class="tab_list">
            <div class="tab_list_item" v-for="item in workData" :key="item.Video.videoId"
              @click="() => handleVideoClick(item, workData)">
              <img :src="item.Video.videoCover" @error="(e) => { e.target.src = defaultCoverImage }" alt="">
              <div class="tab_list_item__like">
                <Icon name="xin-2" size="14" :color="item.WSLCNum.likeNum > 0 ? 'red' : '#ccc'" />
                <span>{{ item.WSLCNum.likeNum }}</span>
              </div>
            </div>
          </div>
          <!-- 暂时没有更多作品 -->
          <div class="commit_list_wrap_more">暂无更多作品</div>
        </TabItem>
        <TabItem :label="`动态${workNum}`">
          <div class="follow">
            <div class="follow_item" v-for="item in dynamicData" :key="item.Video.videoId">
              <div class="follow_item_top">
                <img class="follow_item_top__avatar"
                  src="http://43.138.15.137:3000/assets/avatar/5a544ec7-0301-46b6-96df-0a033fd0cf1c.png" alt="">
                <span class="follow_item_top__username">@{{ item.Video.userNickname }}</span>
              </div>
              <div class="follow_item_desc">{{ item.Video.videoDesc }}</div>
              <div class="follow_item_video">
                <CustomVideo :showProgress="false" :src="item.Video.videoPath">
                </CustomVideo>
              </div>
              <div class="follow_item_bar">
                <div class="follow_item_bar_item">
                  <Icon name="xin-2" :color="item.WSLCNum.likeNum > 0 ? 'red' : '#ccc'" size="18" />
                  <span>{{ item.WSLCNum.likeNum }}</span>
                </div>
                <div class="follow_item_bar_item">
                  <Icon name="pinglun" color="#fff" size="18" />
                  <span>{{ item.WSLCNum.commentNum }}</span>
                </div>
                <div class="follow_item_bar_item">
                  <Icon name="a-fenxiangweifenxiang" color="#fff" size="16" />
                  <span>{{ item.WSLCNum.shareNum }}</span>
                </div>
              </div>
              <div class="follow_item_time">2025-9-28</div>
            </div>
          </div>
        </TabItem>
        <TabItem :label="`喜欢${userlikeNum}`">
          <div class="tab_list">
            <div class="tab_list_item" v-for="item in likeData" :key="item.Video.videoId"
              @click="() => handleVideoClick(item, likeData)">
              <img :src="item.Video.videoCover" alt="">
              <div class="tab_list_item__like">
                <Icon name="aixin" size="14" color="#fff" />
                <span>{{ item.WSLCNum.likeNum }}</span>
              </div>
            </div>
          </div>
          <!-- 暂时没有更多喜欢 -->
          <div class="commit_list_wrap_more">暂无更多喜欢</div>
        </TabItem>
      </Tab>
    </div>
    <!-- 视频播放页 -->
    <!-- 从左到右过渡出现 -->
    <transition name="fade-in-right">
      <VideoPlaybackPage v-if="isShowVideoPlaybackPage" v-model="isShowVideoPlaybackPage" :data="videoPlaybackData">
      </VideoPlaybackPage>
    </transition>
  </div>
</template>
<script setup>
import { ref, onMounted, defineAsyncComponent, reactive } from 'vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import Tab from '@/components/Common/Tabs/index.vue'
import TabItem from '@/components/Common/TabItem/index.vue'
import CustomVideo from '@/components/Common/CustomVideo/index.vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()


// 接受params
const route = useRoute()
const friendId = route.params.friendId
console.log('friendId', friendId)



import { useUserIDStore } from '@/stores/UserID'
const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId

// API 导入
import {
  getFriendListAPIgetFriendProfileAPI,
  followUserAPI
} from '@/api/Home'

import {
  getMyVideoCountAPI,
  followAPI,
  fansAPI,
  likeAPI,
  likeNumAPI,
  workNumAPI,
  getMyDynamicAPI,
  getMyLikeAPI
} from '@/api/my'

// ========== 数据状态 ==========
const userinfo = ref(null)
const workData = ref([])
const dynamicData = ref([])
const likeData = ref([])

// 统计数据
const followNum = ref(0)
const fansNum = ref(0)
const likeNum = ref(0)
const userlikeNum = ref(0)
const workNum = ref(0)

const currentIndex = ref(0)
const isShowVideoPlaybackPage = ref(false)
const videoPlaybackData = ref({ list: [], initialIndex: 0 })

const defaultCoverImage = 'https://img2.baidu.com/it/u=4022145058,3926562442&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1067'
const defaultAvatar = 'https://example.com/default-avatar.png' // 请替换为你的真实默认头像

const scrollContainer = ref(null)

// ========== 用户信息 & 统计数据拆分 ==========
// 仅获取用户基本信息（含 myRelation）
const fetchUserInfo = async () => {
  try {
    const res = await getFriendListAPIgetFriendProfileAPI(friendId, userId)
    userinfo.value = {
      ...res.data,
      userAvatar: 'http://43.138.15.137:3000' + res.data.userAvatar || defaultAvatar
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取统计数据（首次加载用）
const fetchProfileStats = async () => {
  try {
    const [
      followRes,
      fansRes,
      likeRes,
      userLikeRes,
      workCountRes,
      videoCountRes
    ] = await Promise.all([
      followAPI(friendId),
      fansAPI(friendId),
      likeAPI(friendId),
      likeNumAPI(friendId),
      workNumAPI(friendId),
      getMyVideoCountAPI(friendId)
    ])

    followNum.value = followRes.data
    fansNum.value = fansRes.data
    likeNum.value = likeRes.data
    userlikeNum.value = userLikeRes.data
    workNum.value = workCountRes.data
    workData.value = videoCountRes.data.map(item => ({
      ...item,
      Video: {
        ...item.Video,
        userAvatar: 'http://43.138.15.137:3000' + item.Video.userAvatar || defaultCoverImage
      }
    }))
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// ========== 初始化 ==========
const getMyInfo = async () => {
  await fetchUserInfo()
  await fetchProfileStats()
}

// ========== 关注逻辑 ==========
const handleFollowClick = async () => {
  if (!userinfo.value || !userId) return

  const current = userinfo.value.myRelation

  // 推断新状态
  const newRelation = current === 'none' ? 'follow' : 'none'

  try {
    const res = await followUserAPI(userId, friendId)
    if (res.code === 200) {
      // ✅ 直接更新组件内的响应式数据（不是 localStorage！）
      userinfo.value.myRelation = newRelation

      // ✅ 同步更新粉丝数（TA 的粉丝数）
      if (current === 'none') {
        fansNum.value += 1 // 关注：+1
      } else {
        fansNum.value = Math.max(0, fansNum.value - 1) // 取消：-1
      }
    } else {
      console.error('操作失败:', res.msg)
    }
  } catch (error) {
    console.error('网络错误:', error)
  }
}

// ========== Tab 相关 ==========
const getMyDynamic = async () => {
  try {
    const res = await getMyDynamicAPI(userId)
    dynamicData.value = res.data
  } catch (error) {
    console.error('获取动态失败:', error)
  }
}

const getMyLike = async () => {
  try {
    const res = await getMyLikeAPI(userId)
    likeData.value = res.data
  } catch (error) {
    console.error('获取喜欢失败:', error)
  }
}

const handleTabChange = (index) => {
  console.log('切换到 Tab:', index)
  if (index === 1) getMyDynamic()
  if (index === 2) getMyLike()

  // 延迟更新下划线（保持原逻辑）
  setTimeout(() => {
    const tabLine = document.querySelector('.friends_profile_page .tab_line')
    if (!tabLine) return
    const nav = document.querySelector('.friends_profile_page .tabs_nav')
    const tabItems = document.querySelectorAll('.friends_profile_page .tab .tab__text--ellipsis')
    if (nav && tabItems[index]) {
      const activeTab = tabItems[index]
      const navRect = nav.getBoundingClientRect()
      const tabRect = activeTab.getBoundingClientRect()
      const left = tabRect.left - navRect.left
      const width = activeTab.offsetWidth
      const maxLeft = navRect.width - width
      const adjustedLeft = Math.max(0, Math.min(left, maxLeft))
      tabLine.style.transform = `translateX(${adjustedLeft}px)`
      tabLine.style.width = `${width}px`
    }
  }, 50)
}

// ========== 视频播放 ==========
const VideoPlaybackPage = defineAsyncComponent(() =>
  import('@/views/home/VideoPlaybackPage/index.vue')
)

const handleVideoClick = (item, data) => {
  const index = data.findIndex(v => v.Video?.videoId === item.Video?.videoId)
  if (index === -1) return
  videoPlaybackData.value = { list: data, initialIndex: index }
  isShowVideoPlaybackPage.value = true
}

// ========== 返回 ==========
const handleBackClick = () => {
  const from = route.query.from

  // 根据来源页面进行不同的返回逻辑
  if (from === 'home') {
    router.push({ name: 'home' })
  } else if (from === 'follow') {
    router.push({ name: 'follow' })
  } else if (from === 'search') {
    router.push({ name: 'SearchPage' }) // 修复：使用正确的路由名称
  } else {
    // 默认使用go(-1)返回上一个页面
    router.go(-1)
  }
}

// ========== 拖拽 & 滚动（保持原逻辑不变）==========
const backgroundHeight = ref(150)
const backgroundScale = ref(1)
const isPullingDown = ref(false)
const startY = ref(0)

const isAtTop = () => scrollContainer.value?.scrollTop <= 0

const handleTouchStart = (e) => {
  if (!isAtTop()) return
  startY.value = e.touches[0].clientY
  isPullingDown.value = false
}

const handleTouchMove = (e) => {
  if (!isAtTop()) return
  const currentY = e.touches[0].clientY
  const deltaY = currentY - startY.value
  if (deltaY > 0) {
    if (!isPullingDown.value) {
      isPullingDown.value = true
      e.preventDefault()
    }
    const dampingFactor = Math.min(Math.sqrt(deltaY / 100) * 0.4 + 0.1, 1)
    const adjustedDeltaY = (deltaY * dampingFactor) / 2
    const newHeight = Math.min(150 + adjustedDeltaY, 300)
    backgroundHeight.value = newHeight
    backgroundScale.value = 1 + (newHeight - 150) / 150 * 0.1
  }
}

const handleTouchEnd = () => {
  if (isPullingDown.value) {
    backgroundHeight.value = 150
    backgroundScale.value = 1
    isPullingDown.value = false
  }
}

const handleMouseDown = (e) => {
  // 桌面端逻辑（可保留，也可移除）
  // 此处省略，如需可从原代码复制
}

// ========== 生命周期 ==========
onMounted(() => {
  // 打印路由
  console.log('当前路由:', route)

  getMyInfo()

  setTimeout(() => {
    const tabLine = document.querySelector('.friends_profile_page .tab_line')
    if (tabLine) {
      const nav = document.querySelector('.friends_profile_page .tabs_nav')
      const tabItems = document.querySelectorAll('.friends_profile_page .tab .tab__text--ellipsis')
      if (nav && tabItems[0]) {
        const activeTab = tabItems[0]
        const navRect = nav.getBoundingClientRect()
        const tabRect = activeTab.getBoundingClientRect()
        const left = tabRect.left - navRect.left
        const width = activeTab.offsetWidth
        const maxLeft = navRect.width - width
        const adjustedLeft = Math.max(0, Math.min(left, maxLeft))
        tabLine.style.transform = `translateX(${adjustedLeft}px)`
        tabLine.style.width = `${width}px`
      }
    }
  }, 300)
})
// 跳转 TA 关注的页面
const handleShowTAsFocusPage = () => {
  router.push({
    name: 'FriendFollow',
    params: { friendId },
    query: { from: route.query.from || 'home' } // 传递来源信息
  })
}

// TA 粉丝的页面
const handleShowTAsFansPage = () => {
  router.push({
    name: 'Friendsandfans',
    params: { friendId },
    query: { from: route.query.from || 'home' } // 传递来源信息
  })
}
</script>

<style lang="scss" scoped>
.friends_profile_page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #161622;
  z-index: 2025;
  overflow-y: auto;
}

.my_title_background {
  width: 100%;
  height: 150px;
  /* 默认高度，会被动态样式覆盖 */
  position: relative;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  transform-origin: center top;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    /* 确保图片覆盖整个区域 */
  }


}

.profile {
  position: relative;
  width: 100%;
  height: 100%;
  background: #161622;
  transition-timing-function:
    cubic-bezier(0.165, 0.84, 0.44, 1);
  transition-duration: 0ms;
  transform: translate(0px, 0px) scale(1) translateZ(0px);

  .avatar_wrap {
    position: absolute;
    left: 10px;
    top: -15px;
    border-radius: 50%;
    padding: 5px;
    width: 80px;
    height: 80px;
    background: #161622;

    img {
      border-radius: 50%;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .name_wrap {
    position: relative;
    margin: 0 10px;
    padding: 80px 10px 10px;
    border-bottom: 1px solid rgba(41, 40, 37, 0.8);

    .name {
      color: #fff;
      font-size: 18px;
    }

    .subname {
      margin-top: 5px;
      color: #fff;
      font-size: 12px;
    }

    .follow {
      position: absolute;
      top: 24px;
      right: 14px;
      width: 60px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: bold;
      color: #fff;
      padding: 4px 8px;
      border-radius: 2px;
      white-space: nowrap;
      background-color: #f9355f;
      transition: all 0.3s ease-in-out;


      &.active {
        background-color: #393b44;

      }
    }
  }

  .desc_wrap {
    margin: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    gap: 15px;

    .desc_wrap_info {
      display: flex;
      gap: 5px;
      align-items: center;

      .gender {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 2px 8px;
        border-radius: 5px;
        background: rgba(67, 51, 63, 0.7);
        font-size: 10px;
        max-width: 50px;
        color: #8b8c96;
        white-space: nowrap;
      }

      .desc_wrap_info_age {
        font-size: 12px;
      }

      .desc_wrap_info_address {
        font-size: 12px;
      }


    }

    .desc {
      color: #8b8c96;
      font-size: 12px;
    }


  }

  .num_wrap {
    margin: 10px;
    width: 200px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    color: #fff;

    .li {
      font-size: 14px;
    }
  }

  .tab_list {
    display: flex;
    flex-wrap: wrap;

    .tab_list_item {
      position: relative;
      width: 33.33%;
      height: 160px;
      border: 1px solid #000;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .tab_list_item__like {
        position: absolute;
        bottom: 2px;
        left: 6px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #fff;
        gap: 2px;
      }
    }
  }

  .commit_list_wrap_more {
    text-align: center;
    font-size: 12px;
    color: #65676e;
    margin: 14px 0;
  }

  .follow {
    background-color: #161622;
    padding-bottom: 48px;

    .follow_item {
      width: 98%;
      margin: 10px auto 0;
      display: flex;
      flex-direction: column;
      gap: 10px;
      border-bottom: 1px solid #252425;
      padding: 5px;

      .follow_item_top {
        display: flex;
        align-items: center;
        gap: 5px;

        .follow_item_top__avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .follow_item_top__username {
          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_desc {
        font-size: 14px;
        color: #fff;
      }

      .follow_item_video {
        width: 250px;
        height: 350px;
      }

      .follow_item_bar {
        display: flex;
        gap: 10px;

        .follow_item_bar_item {
          display: flex;
          align-items: center;
          gap: 5px;

          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_time {
        font-size: 12px;
        color: #fff;
      }
    }
  }
}

// 添加Tab组件样式
:deep(.tabs) {
  position: relative;
  padding-bottom: 46px;

  .tabs_wrap {
    overflow: hidden;
    height: 44px;

    .tabs_nav {
      height: 100%;
      padding-bottom: 15px;
      -webkit-user-select: none;
      user-select: none;
      display: flex;
      position: relative;
      box-sizing: content-box;

      .tab_line {
        position: absolute;
        bottom: 15px;
        left: 0;
        height: 3px;
        background-color: #39a9ed;
        border-radius: 3px;
        z-index: 1;
        transition: transform 0.3s ease-out, width 0.3s ease-out;
      }
    }
  }

  .tabs_content {
    .tab__panel {
      width: 100%;
    }
  }
}

:deep(.tab) {
  color: #323233;
  font-weight: 600;
  cursor: pointer;
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
  position: relative;
  line-height: 20px;
  font-size: 14px;
  padding: 0 4px;
  height: 100%;
  transition: all .3s ease-out;

  &.tab_active {
    color: #fff;
    font-weight: bold;
  }

  .tab__text--ellipsis {
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    overflow: hidden;
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>